<template>
  <a-modal v-model:open="importModalShowFlag" title="导入" @onCancel="hideImportModal" @ok="hideImportModal">
    <div style="text-align: center; width: 400px; margin: 0 auto">
      <a-button @click="downloadExcel" :disabled="!props.hasDownloadTemplate"> <download-outlined />第一步：下载模板</a-button>
      <br />
      <br />
      <a-upload v-model:fileList="fileList" name="file" :multiple="false" action="#" accept=".xls,.xlsx" :max-count="1" :before-upload="beforeUpload" @remove="handleRemove">
        <a-button>
          <upload-outlined />
          第二步：选择文件
        </a-button>
      </a-upload>

      <br />
      <a-button @click="onImportExcel">
        <ImportOutlined />
        第三步：开始导入
      </a-button>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { message } from 'ant-design-vue'
import { useLoadingStore } from '@/store/modules/loading-store'
import { errorSentry } from '@/lib/error-sentry'
const loadingStore = useLoadingStore()
const emit = defineEmits(['downloadExcel', 'reloadList'])

const props = defineProps({
  importExcel: {
    type: Function,
    required: true
  },
  hasDownloadTemplate: {
    type: Boolean,
    default: true
  },
  extraParams: {
    type: Object,
    default: () => ({}) // 默认为空对象
  }
})
const { importExcel } = props
// 导入弹窗
const importModalShowFlag = ref(false)

const fileList = ref([])
// 显示导入
function showImportModal() {
  fileList.value = []
  importModalShowFlag.value = true
}

// 关闭 导入
function hideImportModal() {
  importModalShowFlag.value = false
}

function handleRemove(file) {
  const index = fileList.value.indexOf(file)
  const newFileList = fileList.value.slice()
  newFileList.splice(index, 1)
  fileList.value = newFileList
}
function beforeUpload(file) {
  fileList.value = [...(fileList.value || []), file]
  return false
}

function downloadExcel() {
  emit('downloadExcel')
}
function reloadList() {
  emit('reloadList')
}
async function onImportExcel() {
  if (fileList.value.length === 0) {
    message.error('请选择文件!')
    return
  }
  const formData = new FormData()
  fileList.value.forEach((file) => {
    formData.append('file', file.originFileObj)
  })
  // 动态添加额外的参数
  for (const key in props.extraParams) {
    formData.append(key, props.extraParams[key])
  }

  loadingStore.show()
  try {
    const res = await importExcel(formData)
    message.success(res.msg)
    hideImportModal()
    reloadList()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}

defineExpose({
  showImportModal
})
</script>
